<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Manage extends MY_Controller {
	public function index() {
		$this -> renderView('manage/index');
	}

	/**
	 * symbol
	 */
	public function symbol() {
		$this -> load -> model('repos/symbolmodel', 'SymbolModel');
		$data['data']['arrSymbol'] = $this -> SymbolModel -> getSymbol();
		$data['viewPath'] = 'manage/symbol/index';
		$data['isLoadCalendar'] = true;
		$this -> renderView('manage/index', $data);
	}

	/**
	 * Add new symbol
	 **/
	public function doaddsymbols() {
		if ($this -> input -> post()) {
			$strSymbol = $this -> input -> post('txtnewsymbol', true);
			if ($strSymbol != '') {
				$strSymbol = trim($strSymbol);
				if (strlen($strSymbol) > 0) {
					$arrSymbol = explode("\n", $strSymbol);
					$arrEntitySymbol = array();
					foreach ($arrSymbol as $item) {
						$item = trim($item);
						if (!empty($item)) {
							$this -> load -> model('entities/symbolentity');
							$entitySymbol = new SymbolEntity();
							$entitySymbol -> setUrlVal($item);
							array_push($arrEntitySymbol, $entitySymbol);
						}
					}

					if (count($arrEntitySymbol) > 0) {
						//check if inserted
						$this -> load -> model('repos/symbolmodel', 'SymbolModel');
						$result = $this -> SymbolModel -> insertSymbols($arrEntitySymbol);
						if ($result > 0) {
							echo "<span class='success'>Insert successful!</span>";
						} else {
							echo "<span class='error'>Insert fail. Symbols may be already exists.</span>";
						}
					} else {
						echo "<span class='error'><strong>Symbol</strong> was invalid !</span>";
					}
				} else {
					echo "<span class='error'><strong>Symbol</strong> can not be blank.</span>";
				}
			} else {
				echo "<span class='error'><strong>Symbol</strong> can not be blank.</span>";
			}
			return;
		}
		show_404();
	}

	/**
	 * Get symbol list , return hmtl
	 **/
	public function getsymbolslist() {
		$this -> load -> model('repos/symbolmodel', 'SymbolModel');
		$data['arrSymbol'] = $this -> SymbolModel -> getSymbol();
		$this -> load -> view("manage/symbol/getsymbolslist", $data);
	}

	/**
	 *
	 **/
	public function deletesymbol() {
		$res = 0;
		$id = $this -> input -> post('id', true);
		$id = trim($id);
		if ($id != '') {
			$this -> load -> model('repos/symbolmodel', 'SymbolModel');
			$id = base64_decode($id);
			$res = $this -> SymbolModel -> deletesymbol($id);
		}

		echo $res;
	}

	/**
	 * Get data for symbols
	 **/
	public function newdataforsymbol() {
		//check if invalid post
		if ($this -> input -> post() == false) {
			echo 0;
			return;
		}
		//determind which symbols need get data.
		$sSymbol = $this -> input -> post('val', true);
		if (!isset($sSymbol) || empty($sSymbol)) {
			echo -1;
			return;
		} else {
			$sSymbol = trim($sSymbol);
		}

		//validate startdate enddate
		$startdate = trim($this -> input -> post('startdate', true));
		$enddate = trim($this -> input -> post('enddate', true));
		try {
			$startdate = new DateTime($startdate, new DateTimeZone(TIMEZONE));
			$enddate = new DateTime($enddate, new DateTimeZone(TIMEZONE));
			if ($enddate < $startdate) {
				throw new Exception('E_0001');
			}
		} catch (exception $ex) {
			echo -2;
			return;
		}

		//download csv content
		$cnx_symbols = unserialize(CNX_SYMBOLS);
		$aReturnData = $this -> downloadData($sSymbol, $cnx_symbols, $startdate, $enddate);
		if (empty($aReturnData)) {
			echo -3;
			return;
		}

		//parse to entity
		//get array symbols details
		$this -> load -> model('repos/symbolmodel', 'SymbolModel');
		$this -> load -> library('csvparser');
		$objSymbolDetails = $this -> SymbolModel -> getSymbolDetails($sSymbol);
		$filePath = TEMP_CSV_PATH . $sSymbol . TEMP_CSV_FILE_EXT;
		$aSymbolObject = array();

		if (in_array($sSymbol, $cnx_symbols)) {
			$aSymbolObject = $this -> csvparser -> parserToEntity2($objSymbolDetails -> getId(), $filePath);
		} else {
			$aSymbolObject = $this -> csvparser -> parserToEntity($objSymbolDetails -> getId(), $filePath);
		}
		unlink($filePath);

		if (!empty($aSymbolObject)) {
			$result = $this -> SymbolModel -> insertCompanyDetailsForInstall($aSymbolObject, $startdate, $enddate);
			if ($result > 0) {
				echo 1;
				return;
			} else {
				echo -4;
				return;
			}
		}
		echo -5;
		return;
	}

	private function downloadData($item, $cnx_symbols, $startdate, $enddate) {
		$this -> load -> library('download');
		$aCurlInfo = array();
		$oDownload = new Download();
		$oDownload -> setAgent($this -> getAgent());

		//setup curl data
		$sym = $item;
		$sym = $this -> encodeURL($sym);
		$aInfo = array();
		$aInfo['symbol'] = $item;
		if (in_array($item, $cnx_symbols)) {
			$tempEnddate = new DateTime('now', new DateTimeZone(TIMEZONE));
			if ($enddate > $tempEnddate) {
				$enddate = $tempEnddate;
			}
			$aInfo['remark'] = false;
			$aInfo['url'] = CSV_HOST_CNX;
			$aInfo['queryString'] = $sym . $startdate -> format('d-m-Y') . '-' . $enddate -> format('d-m-Y') . TEMP_CSV_FILE_EXT;
		} else {
			$tempEnddate = date('Y-m-d', strtotime(' +1 day'));
			$tempEnddate = new DateTime($tempEnddate, new DateTimeZone(TIMEZONE));
			$aInfo['remark'] = true;
			$aInfo['url'] = CSV_HOST;
			$aInfo['queryString'] = "symbol={$sym}&fromDate={$startdate->format('d-M-Y')}&toDate={$tempEnddate->format('d-M-Y')}&datePeriod=unselected&hiddDwnld=true";
		}
		array_push($aCurlInfo, $aInfo);
		return $oDownload -> exec($aCurlInfo);
	}

	/**
	 * watchlist
	 */
	public function watchlist() {
		$this -> load -> model('repos/symbolmodel', 'SymbolModel');
		$this -> load -> model('repos/watchlistmodel', 'WLModel');
		$data['arrSymbol'] = $this -> SymbolModel -> getSymbol();
		$data['arrWatchList'] = $this -> WLModel -> getWatchLists();
		$data['viewPath'] = 'manage/watchlist/index';
		$this -> renderView('manage/index', $data);
	}

}
?>